package com.shen.demo.demos.web.compont.webSocket;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.adapter.standard.StandardWebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component

public class HttpAuthHandler extends TextWebSocketHandler {

    /*// 用于保存所有连接的 WebSocket 会话
    private static final Set<WebSocketSession> sessions = new HashSet<>();*/
    /*private static final ObjectMapper objectMapper = new ObjectMapper();*/

    /**
     * socket 建立成功事件
     *
     * @param session 连接的 WebSocket 会话
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        /*Object whareaId = session.getAttributes().get("whareaId");*/
        Object sessionId = session.getAttributes().get("session_id");
        if (sessionId != null) {
            // 用户连接成功，放入在线用户缓存
            WsSessionManager.add(sessionId.toString(), session);
        } else {
            throw new RuntimeException("用户登录已经失效!");
        }
    }

    /**
     * 接收消息事件
     *
     * @param session 连接的 WebSocket 会话
     * @param message 信息
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 获得客户端传来的消息
        String payload = message.getPayload();
        Object whareaId = session.getAttributes().get("whareaId");
        /*Object sessionId = session.getAttributes().get("sessionId");*/
        System.out.println("server客户端 "+whareaId+"接收到 服务器  发送的 " + payload);
        session.sendMessage(new TextMessage("server "+whareaId+"发送给  服务器   消息 " + payload + " " + LocalDateTime.now()));
    }

    /**
     * socket 断开连接时
     *
     * @param session 被关闭的 WebSocket 会话
     * @param status 会话状态
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        /*Object whareaId = session.getAttributes().get("whareaId");*/
        Object sessionId = session.getAttributes().get("session_id");
        if (sessionId != null) {
            // 用户退出，移除缓存
            WsSessionManager.remove(sessionId.toString());
        }
    }
    /**
     * 广播消息给所有连接的客户端（广播）
     *
     * @param message 数据集
     */
    public static void broadcast(JSONObject message) {
        ConcurrentHashMap<String, WebSocketSession> sessionPool = WsSessionManager.SESSION_POOL;
        for (WebSocketSession session : sessionPool.values()) {
            if (session.isOpen()) {
                try {
                    // 将 JSONObject 转换为 JSON 字符串
                    String jsonString = message.toString();
                    session.sendMessage(new TextMessage(jsonString));
                } catch (IOException e) {
                    // 记录异常信息，可以选择重新抛出或忽略
                    System.err.println("Failed to send message to session: " + session.getId());
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 广播消息给所有连接的客户端（定点广播）-- 暂时无法实现：whareaID相同，值被覆盖
     *
     * @param message 返回数据集
     */
    public static void broadcastToPage(String whareaId,JSONObject message) {
        ConcurrentHashMap<String, WebSocketSession> sessionPool = WsSessionManager.SESSION_POOL;
        for (WebSocketSession session : sessionPool.values()) {
            boolean isWhreaIdMatch = false;
            isWhreaIdMatch = isWhreaIdMatch(session, whareaId);
            if (session.isOpen() && isWhreaIdMatch) {
                try {
                    // 将 JSONObject 转换为 JSON 字符串
                    String jsonString = message.toString();
                    session.sendMessage(new TextMessage(jsonString));
                } catch (IOException e) {
                    // 记录异常信息，可以选择重新抛出或忽略
                    System.err.println("Failed to send message to session: " + session.getId());
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 发送消息到指定页面(点对点)
     *
     * @param key       页面ID或其他唯一标识符
     * @param message   要发送的消息
     */
    public static void sendMessageToPage(String key, JSONObject message) {
        ConcurrentHashMap<String, WebSocketSession> sessionPool = WsSessionManager.SESSION_POOL;
        WebSocketSession session = sessionPool.get(key);
        if (session != null && session.isOpen()) {
            try {
                /*String json = objectMapper.writeValueAsString(message);*/
                session.sendMessage(new TextMessage(message.toJSONString()));
            } catch (IOException e) {
                // 发送消息出现异常处理
                e.printStackTrace();
            }
        }
    }
    /**
     * 判断是否是目标页面(匹配对应参数whareaId相同session)
     *
     * @param session 会话
     * @param whareaIdValue 库区值
     * @return boolean
     */

    private static boolean isWhreaIdMatch(WebSocketSession session, String whareaIdValue) {
        if (session instanceof StandardWebSocketSession) {
            StandardWebSocketSession standardSession = (StandardWebSocketSession) session;
            Map<String, Object> attributes = standardSession.getAttributes();
            return attributes.containsKey("whareaId") && attributes.get("whareaId").equals(whareaIdValue);
        }
        return false;
    }
//    /**
//     * 向指定的客户端发送消息
//     *
//     * @param message
//     * @param key
//     * @throws Exception
//     */
//    public static void sendMessageToClient(String message, String key) throws Exception {
//        logger.info("Sending message to client with key {}: {}", key, message);
//        WebSocketSession session = SESSION_POOL.get(key);
//        if (session != null && session.isOpen()) {
//            session.sendMessage(new TextMessage(message));
//        } else {
//            logger.warn("Session not found or closed for key: {}", key);
//        }
//    }


    
}

